from machine import Pin, I2C
import utime

# DS3231 的 I2C 地址
DS3231_ADDR = 0x68

# 初始化 I2C
i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000)  # D1=SCL, D2=SDA

def bcd_to_dec(bcd):
    """将BCD格式转换为十进制"""
    return (bcd // 16) * 10 + (bcd % 16)

def dec_to_bcd(dec):
    """将十进制转换为BCD格式"""
    return (dec // 10) * 16 + (dec % 10)

def set_time(year, month, day, hour, minute, second, weekday=0):
    """设置RTC时间"""
    data = bytearray(7)
    data[0] = dec_to_bcd(second)  # 秒
    data[1] = dec_to_bcd(minute)  # 分
    data[2] = dec_to_bcd(hour)    # 时
    data[3] = dec_to_bcd(weekday) # 星期 (1-7, 1=周日)
    data[4] = dec_to_bcd(day)     # 日
    data[5] = dec_to_bcd(month)   # 月
    data[6] = dec_to_bcd(year - 2000)  # 年 (00-99)
    
    i2c.writeto_mem(DS3231_ADDR, 0, data)

def get_time():
    """读取RTC时间"""
    data = i2c.readfrom_mem(DS3231_ADDR, 0, 7)
    second = bcd_to_dec(data[0] & 0x7F)
    minute = bcd_to_dec(data[1])
    hour = bcd_to_dec(data[2] & 0x3F)
    weekday = bcd_to_dec(data[3])
    day = bcd_to_dec(data[4])
    month = bcd_to_dec(data[5])
    year = bcd_to_dec(data[6]) + 2000
    
    return (year, month, day, weekday, hour, minute, second)

def get_temperature():
    """读取温度"""
    data = i2c.readfrom_mem(DS3231_ADDR, 0x11, 2)
    temp = data[0] + (data[1] >> 6) * 0.25
    return temp

# 示例使用
# 设置时间 (年, 月, 日, 时, 分, 秒, 星期)
# 取消下面一行的注释来设置时间 (只需要设置一次)
# set_time(2023, 11, 15, 12, 0, 0, 3)  # 2023年11月15日12:00:00 星期三
if __name__ == "__main__":
    while True:
        year, month, day, weekday, hour, minute, second = get_time()
        temp = get_temperature()
        
        print("{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d} 星期{} 温度: {:.1f}°C".format(
            year, month, day, hour, minute, second, weekday, temp))
        
        utime.sleep(1)
    